<?php

namespace models;

//如
// 1. http://cd.meituan.com/deal/36714900.html
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use util\CommonUtil;
use util\Constant;

class MeiTuanDealSpider extends BaseSpider {

    public $referUrl;   // refer Url

    // 初始化webUrl、apiUrl
    function __construct($url, $ua){
        $this->ua = $ua;
        $this->webUrl = $url;
        $url = explode('?',$url)[0];
        $id = 0;
        if(preg_match('/([0-9]+)/',$url,$matches)){
            $id = $matches[1];
        }
        if ($id != 0) {
            $str2 = explode('//',$url)[1];
            $str3 = explode('/',$str2)[0];
            $this->apiUrl = "http://".$str3.'/deal/feedbacklist/'.$id."/all/all/0/default/59?limit=10&showpoititle=1&offset=0";
            $this->referUrl = "http://".$str3;
        }

    }

    // 获取评论列表，仅获取10条
    public function getComments(){

        $arr = array();
        try {

            if (empty($this->apiUrl)) return [];
            CommonUtil::echoStr("\n{$this->webUrl}\n");
            CommonUtil::echoStr("\n{$this->apiUrl}\n");

            // start Firefox with 5 second timeout
            $host = 'http://localhost:4444/wd/hub'; // this is the default
            $capabilities = DesiredCapabilities::chrome();
            $options = new ChromeOptions();
            $options->addArguments(["user-agent={$this->ua}"]);
            $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
            $driver = RemoteWebDriver::create($host, $capabilities, Constant::$CONNECTION_TIMEOUT_IN_MS);
            $driver->manage()->timeouts()->implicitlyWait(Constant::$IMPLICITLY_WAIT);
            $driver->manage()->window()->maximize();    //将浏览器最大化

            $driver->get($this->referUrl);   //先访问网页，获取到cookie权限
            $cookies = $driver->manage()->getCookies();
            $cookieStr = '';
            foreach ($cookies as $cookie) {
                $cookieStr .= "{$cookie['name']}={$cookie['value']};";
            }

            $ch = curl_init();
            $timeout = 30;
            curl_setopt ($ch, CURLOPT_URL, $this->apiUrl);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
            curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
            curl_setopt($ch, CURLOPT_REFERER, $this->referUrl);
            curl_setopt($ch,CURLOPT_COOKIE,$cookieStr);
            $file_contents = curl_exec($ch);
            curl_close($ch);
            if(empty($file_contents)) return;
            $fileJson = json_decode($file_contents);
            $data = $fileJson->data;
            $ratelistHtml = $data->ratelistHtml;
            $html = str_get_html($ratelistHtml);

            $liList = $html->find('li[class=J-ratelist-item rate-list__item cf]');
            foreach ($liList as $li){
                $avatar = $li->find('img[class=avatar]',0)->attr['src'];//用户头像地址
                $name = $li->find('span[class=name]',0)->innertext;//用户昵称
                $time = $li->find('span[class=time]',0)->innertext;//评论时间
                $content = $li->find('p[class=content]',0)->innertext;//用户评论
                $pic_thumbnail_list = $li->find('li');//评论图片列表
                $picUrlStr = '';
                for($i = 0;$i<count($pic_thumbnail_list);$i++){
                    $img = $pic_thumbnail_list[$i]->attr['data-src'];
                    if (!empty($picUrlStr)) $picUrlStr .= ',';
                    $picUrlStr .= $img;
                }
                $obj = array();
                $obj['head'] = CommonUtil::replace2https($avatar);   //头像
                $obj['nickname'] = trim($name);  //昵称
                $obj['content'] = trim($content);    //评论内容
                $obj['comment_time'] = trim($time);   //评论时间
                $obj['pic_urls'] = $picUrlStr;   //评论图片
                $arr[] = $obj;

            }

            CommonUtil::shutdownChrome($driver);

        } catch (\Exception $e) {

            if (!empty($driver)){
                $driver->manage()->deleteAllCookies();  //清除COOKIES，主要是清除百度的“访客标识码”
            }
            CommonUtil::shutdownChrome($driver);

            CommonUtil::logException($e);   //记录异常信息
            CommonUtil::echoStr($msg = "\n发生异常，过滤本次任务~\n");
        }

        return $arr;

    }
	
}